package com.ptppay.cf.coin.service.btc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.wallet.Wallet;

import com.ptppay.cf.btc.CFBtc;
import com.ptppay.cf.core.business.service.CFService;

import cn.finder.bitcoin.Btc;
import cn.finder.bitcoin.BtcTools;
import cn.finder.ui.webtool.QueryCondition;
import cn.finder.wae.business.domain.Message;
import cn.finder.wae.business.domain.TableQueryResult;
import cn.finder.wae.business.dto.MapParaQueryConditionDto;
import cn.finder.wae.common.comm.AppApplicationContextUtil;
import cn.finder.wae.queryer.handleclass.QueryerDBAfterClass;

/**
 * @author: finder
 * @function: transfer coin
 * 
 */

public class TransferCoinAfterClass extends QueryerDBAfterClass {

	CFService cFService = AppApplicationContextUtil.getContext().getBean("cFService", CFService.class);

	private Logger logger = Logger.getLogger(TransferCoinAfterClass.class);

	@Override
	public TableQueryResult handle(TableQueryResult tableQueryResult, long showTableConfigId,
			QueryCondition<Object[]> condition) {
		super.handle(tableQueryResult, showTableConfigId, condition);
		logger.info("===" + this.getClass());
		@SuppressWarnings("unchecked")
		Map<String, Object> data = ((MapParaQueryConditionDto<String, Object>) condition).getMapParas();

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

		Map<String, Object> returnItem = new HashMap<String, Object>();
		resultList.add(returnItem);
		tableQueryResult.setResultList(resultList);

		tableQueryResult.setPageIndex(condition.getPageIndex());
		tableQueryResult.setPageSize(condition.getPageSize());
		tableQueryResult.setCount(1l);

		/*
		 * String pre_txid = ""; try { pre_txid =
		 * data.get("pre_txid").toString(); } catch (Exception e) {
		 * 
		 * tableQueryResult.getMessage().setResultCode(Message.
		 * StatusCode_PARAMS_ERROR);
		 * tableQueryResult.getMessage().setMsg("param pre_txid is err"); }
		 */


		String wallet = ""; // equipment code
		try {
			wallet = data.get("wallet").toString();
		} catch (Exception e) {

			tableQueryResult.getMessage().setResultCode(Message.StatusCode_PARAMS_ERROR);
			tableQueryResult.getMessage().setMsg("param wallet is err");
		}

		String coin_amt = ""; //

		try {
			coin_amt = data.get("coin_amt").toString();
		} catch (Exception e) {
			tableQueryResult.getMessage().setResultCode(Message.StatusCode_PARAMS_ERROR);
			tableQueryResult.getMessage().setResultMsg("param [coin_amt] is error");
		}

		/*
		 * String money_amt = ""; //
		 * 
		 * try { money_amt = data.get("money_amt").toString(); } catch
		 * (Exception e) { tableQueryResult.getMessage().setResultCode(Message.
		 * StatusCode_PARAMS_ERROR); tableQueryResult.getMessage().
		 * setResultMsg("param [money_amt] is error"); }
		 */

		/*
		 * String act_money_amt = ""; //
		 * 
		 * try { act_money_amt = data.get("act_money_amt").toString(); } catch
		 * (Exception e) { tableQueryResult.getMessage().setResultCode(Message.
		 * StatusCode_PARAMS_ERROR); tableQueryResult.getMessage().
		 * setResultMsg("param [act_money_amt] is error"); }
		 */

		// String coin_type = "BTC"; //

		/*
		 * try { coin_type = data.get("coin_type").toString(); } catch
		 * (Exception e) { tableQueryResult.getMessage().setResultCode(Message.
		 * StatusCode_PARAMS_ERROR); tableQueryResult.getMessage().
		 * setResultMsg("param [coin_type] is error"); }
		 */

		String wallet_id = ""; //

		try {
			wallet_id = data.get("wallet_id").toString();
		} catch (Exception e) {
			tableQueryResult.getMessage().setResultCode(Message.StatusCode_PARAMS_ERROR);
			tableQueryResult.getMessage().setResultMsg("param [wallet_id] is error");
		}
		if (tableQueryResult.getMessage().getResultCode() == Message.StatusCode_OK) {

			try {

				String tx_hash = "";

				CFBtc cfBtc = new CFBtc();
				long balance = cfBtc.getWalletBalance(wallet_id);

				if (balance >= (Double.parseDouble(coin_amt) * 100000000)) {
					try {

						Wallet w = cfBtc.getWallet(wallet_id);

						Transaction trans = BtcTools.transfer(w, wallet, Double.parseDouble(coin_amt),
								Btc.get().getPeerGroup(), Btc.get().getNetworkParameters());
						tx_hash = trans.getHashAsString();

					} catch (Exception e) {
						tableQueryResult.getMessage().setResultCode(Message.StatusCode_ServerError);
						tableQueryResult.getMessage().setMsg("buy.transfer.do.error");
					}

				} else {

					tableQueryResult.getMessage().setResultCode(Message.StatusCode_ServerError);
					tableQueryResult.getMessage().setMsg("buy.transfer.failure.notenough");
				}

				if (!StringUtils.isEmpty(tx_hash)) {
					// success
					// update to db
					returnItem.put("tx_hash", tx_hash);

				} else {
					returnItem.put("tx_hash", "");
				}

			} catch (Exception e) {

				tableQueryResult.getMessage().setResultCode(Message.StatusCode_ServerError);
				tableQueryResult.getMessage().setMsg("buy.transfer.failure");
			}

		}

		return tableQueryResult;

	}

	@Override
	public void setJDBCDataSource(DataSource dataSource) {
		super.setJdbcDataSource(dataSource);
	}

}
